import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router';
import layout from '@/layout/index.vue';
import store from '../store';
import { isTokenExpired } from '../util/util';
/**
 * meta 配置说明
 * title: 标题，必选
 * icon: 图标，可选
 * hidden: 是否隐藏，可选  说明是否在侧栏菜单显示
 * cache: 是否缓存，可选 注意ture是不缓存
 * permissions: 权限，可选
 */
const staticRoutes : RouteRecordRaw[] = [
	{
		path: '/login',
		name: 'login',
		component: () => import('@/views/login/login.vue'),
		meta: {
			title: '登录',
			hidden: true,
			cache:true
		}
	},
	{
		path: '/404',
		name: '404',
		component: () => import('@/views/404.vue'),
		meta: {
			title: '404',
			hidden: true,
			cache:true
		}
	}
];

// 加载静态路由
const router = createRouter({
	history: createWebHashHistory(),
	routes: staticRoutes
});

// 获取用户权限并过滤路由
// const filterRoutesByPermissions = (routes : any[], permissions : string[]) => {
// 	return routes.filter(route => {
// 		// 过滤出有权限的路由
// 		if (route.meta && route.meta.permissions) {
// 			// 判断当前用户是否有该路由所需的权限
// 			return route.meta.permissions.some((permission : string) => permissions.includes(permission));
// 		}
// 		return true;  // 如果路由没有设置权限，则默认显示
// 	});
// };

// 动态添加路由
const addDynamicRoutes = async (permissions : any[]) => {
	// const routeList = await getRoutes();
	// const filteredRoutes = filterRoutesByPermissions(routeList, permissions);
	const filteredRoutes = permissions;
	filteredRoutes.forEach(route => {
		const routeConfig : RouteRecordRaw = {
			path: route.path,
			name: route.name,
			meta: route.meta,
			redirect: route.redirect,
			component: layout,
			children: []
		};
		// 懒加载组件
		if (route.children && route.children.length > 0) {
			// 如果有子路由，递归添加
			routeConfig.children = route.children.map((child:any) => ({
				path: child.path,
				name: child.name,
				component: () => import(`@/views/${route.name}/${child.component}.vue`), 
				meta: child.meta,
			}));
		}
		router.addRoute(routeConfig);
	});
};

let hasAddedRoutes = false
const notFoundRoute = {
	path: '/:pathMatch(.*)*',
	redirect: '/404',
};

// 登录后的路由处理
router.beforeEach(async (to, from, next) => {
	if(to.path == '/login'){
		next()
		return
	}
	const token = localStorage.getItem('token');
	if(isTokenExpired(token)){
		next('/login')
		return
	}
	if (!hasAddedRoutes) {
		await store.dispatch('route/fetchMenuList')
		await addDynamicRoutes(store.getters['route/getMenuList'])
		router.addRoute(notFoundRoute)
		hasAddedRoutes = true
		next({ ...to, replace: true })
		return
	}
	
	if (!to.meta.cache) {
		store.dispatch('route/addRoute', to);
	}
	next()
});

export default router;